import React, { Component } from "react";
import { Link, Route, Switch } from "react-router-dom";

class Home extends Component {
  render() {
    return <div>这是home组件 - {this.props.match.params.id}</div>;
  }
}

class About extends Component {
  render() {
    // query的传参需要用到this.props.location.search
    // console.log(this.props);
    // const {
    //   location: { search },
    // } = this.props;
    // const query = search.slice(1); // "a=3&b=4"

    // const params = new URLSearchParams(query);
    // const a = params.get("a");

    // 这个构造函数可以传入一个完整的url
    // const obj = new URL("http://localhost:3000/about?a=3&b=4");
    // console.log(obj.searchParams.get("b"));

    // 这个构造函数可以传入query a=3&b=4
    // const obj = new URLSearchParams("a=3&b=4");
    // console.log(obj.get("b"));

    return <div>这是About组件</div>;
  }
}

class Mine extends Component {
  render() {
    console.log(this.props);
    return <div>这是Mine组件</div>;
  }
}

class App extends Component {
  render() {
    return (
      <>
        <h2>react-router-传参</h2>
        <ul>
          <li>
            {/* 动态路由传参 */}
            <Link to="/home/223">首页</Link>
          </li>
          <li>
            {/* query的传参 */}
            <Link to="/about?a=3&b=4">关于页</Link>
          </li>
          <li>
            <Link
              // state也可以做url的传参，state是一个对象，里面可以随意发挥
              // 是一种在url地址上面看不到的一种传参
              to={{
                pathname: "/mine",
                search: "?x=10&y=20",
                hash: "#abc",
                state: {
                  name: "zhangsan",
                  age: 20,
                },
              }}
            >
              我的页
            </Link>
          </li>
        </ul>

        <hr />

        <Switch>
          <Route path="/home/:id" component={Home} exact></Route>
          <Route path="/about" component={About}></Route>
          <Route path="/mine" component={Mine}></Route>
        </Switch>
      </>
    );
  }
}

export default App;
